#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <string.h>

using std::cout;
using std::endl;

int main()
{
    int pipetable[2] = {0};
    pipe(pipetable);

    pid_t id = fork();
    assert(id >= 0);
    if (id == 0)
    {
        // child 读
        close(pipetable[1]);
        char buffer[1024];
        while (true)
        {
            sleep(20);
            read(pipetable[0], buffer, sizeof(buffer));
            cout << "child process[" << getpid() << "]" << "\t" << buffer <<endl;
        }
        close(pipetable[0]);
    }
    // father 写
    close(pipetable[0]);
    char buffer[1024];
    int count = 0;
    while (true)
    {
        snprintf(buffer, sizeof(buffer), "father process[%d], %d", getpid(), count);
        count++;
        write(pipetable[1], buffer, strlen(buffer));
        //sleep(1);
    }
    close(pipetable[1]);

    return 0;
}